<?php
/**
 * Created by PhpStorm.
 * User: 86173
 * Date: 2020-08-20
 * Time: 17:09
 */
require_once "./lib/DB.php";
date_default_timezone_set('PRC');
if(isset($_GET['action'])){
    $dbObj =  new \libs\DB("user");
    $redis = new Redis();
    $redis->connect("127.0.0.1",6379);
    $redis->auth("tangwei");
    switch($_GET['action']){
        case "register"://注册
            //1.接收数据
            $data = $_POST;
            //2.验证数据
             $data = validateData($data);
             $queryRes = $dbObj->where("name",$data['name'],"=")->limit(0,1)->query();
             if(!isset($queryRes["code"])){
                 echo json_encode(["code"=>404,"msg"=>"用户名已存在"]);die;
             }
             //3.处理数据
            $data["password"] = md5($data["password"]);
             $data['inrod'] = htmlspecialchars($data['inrod']);
            $data['create_time'] = date("Y-m-d H:i:s",time());

            //增加数据
            $result = $dbObj->insert($data);
            if($result['code'] == 1){
                echo json_encode(["code"=>200,"msg"=>"注册成功"]);
            }else{
                echo json_encode(["code"=>200,"msg"=>"注册失败"]);
            }
        break;
        case "login"://登录
            $data = $_POST;
            //判断用户名，密码是否为空
            if(empty($data['name']) || empty($data["password"])){
                echo json_encode(["code"=>401,"msg"=>"用户名、或密码不能为空"]); die;
            }
            //判断用户是否存在
            $queryRes = $dbObj->where("name",$data['name'],"=")->limit(0,1)->query();
            if(isset($queryRes["code"])){
                echo json_encode(["code"=>404,"msg"=>"用户名不已存在"]);die;
            }
            //查看用户是否被禁用
            $errorCount = $redis->get($data['name']);
            if($errorCount >= 5){
                echo json_encode(["code"=>401,"msg"=>"该用户已被禁用,过一天后在试"]);die;
            }
            //判断密码是否正确
            $queryRes = $dbObj
                ->where("name",$data['name'])
                ->where("password",md5($data['password']))
                ->limit(0,1)
                ->query();
            if(isset($queryRes["code"])){
                if(empty($errorCount)){
                    $redis->set($data['name'],1,nowTime_12());
                }else{
                    $redis->incr($data['name']);
                }
                echo json_encode(["code"=>404,"msg"=>"密码错误"]);die;
            }
            //登录成功存cookie
            setcookie("userId",$queryRes[0]["id"],time() + 10 * 60);
            setcookie("userInfo",json_encode($queryRes[0]),time() + 10 * 60);
            echo json_encode(["code"=>200,"msg"=>"登录成功"]);
        break;
        case "add":
            $userId = isLogin();//判断用户是否登录
            if($redis->exists("addCount:".$userId) && $redis->get("addCount:".$userId) > 5){
                echo json_encode(["code"=>401,"msg"=>"该用户当天留言次数已达到上限"]);die;
            }
            $data = $_POST;
            $validateArticle = ["title"=>"标题","content"=>"文章内容"];
            foreach($data as $key=>$value){
                if(empty($data[$key])){
                    echo json_encode(["code"=>401,"msg"=>$validateArticle[$key]."不能为空"]);die;
                }
            }
            $data['content'] = htmlspecialchars($data['content']);
            $data['create_time'] = date("Y-m-d H:i:s",time());
            $data["user_id"] = $userId;
            $result = \libs\DB::table("message")->insert($data);
            if($result['code'] == 1){
                if($redis->exists("hotMessage")){
                    $articleLen = $redis->lLen("hotMessage");
                    if($articleLen >= 10){
                        $redis->lPop("hotMessage");
                    }
                    $redis->rPush("hotMessage",$result['insert_id']);
                }else{
                    $redis->rPush("hotMessage",$result['insert_id']);
                }
                if($redis->exists("addCount:".$userId)){
                    $redis->incr("addCount:".$userId);
                }else{
                    $redis->set("addCount:".$userId,1,nowTime_12());
                }
                echo json_encode(["code"=>200,"msg"=>"发帖成功"]);
            }else{
                echo json_encode(["code"=>200,"msg"=>"发帖失败"]);
            }
         break;
        case "index"://主页面
          $userId = isLogin();//判断用户是否登录
            //遍历留言
          $page = $_GET['page'] ?? 1;
          $limit = $_GET['limit'] ?? 2;
          $start = floor($page * $limit - $limit);
          $data = \libs\DB::table("message")
              ->where("status",0,"<>")
              ->order_by("create_time","desc")
              ->limit($start,$limit)
              ->query();
          $userData = \libs\DB::table("user")->query();
          $userName = array_column($userData,'name','id');
          $data = dealName($data,$userName);
          //获取最热文章
          $hotMsgId = $redis->lRange("hotMessage",0,-1);
          if(empty($hotMsgId)){
              $hotRes = "";
          }else{
              $hotRes = \libs\DB::table("message")->in("id",$hotMsgId)->query();
              $hotRes = dealName($hotRes,$userName);
          }
          $count= count(\libs\DB::table("message") ->where("status",0,"<>")->query());
          echo json_encode(["code"=>0,"msg"=>"ok","count"=>$count,"data"=>$data,"hot"=>$hotRes]);
        break;
        default:
            echo json_encode(["code"=>401,"msg"=>"非法操作"]);
        break;
    }
}else{
    echo json_encode(["code"=>401,"msg"=>"非法操作"]);
}
/**
 * 验证注册数据
 * @param $data
 * @return mixed
 */
function validateData($data){
    $dataInfo = ["nickname"=>"呢称","name"=>"用户名","password"=>"密码","inrod"=>"用户简介"];
    foreach($data as $key=>$value){
        if(empty($data[$key])){
            echo json_encode(["code"=>401,"msg"=>$dataInfo[$key]."不能为空"]);die;
        }
    }
    return $data;
}

/**
 * 验证用户是否登录
 */
function isLogin(){
    if(!isset($_COOKIE['userId'])){
        echo json_encode(["code"=>401,"msg"=>"用户未登录"]);die;
    }
    return $_COOKIE['userId'];
}

/**
 * 获取当前时间到凌晨多少秒
 * @return false|int
 */
function nowTime_12(){
    $now = time();
    $over = strtotime(date("y-m-d 23:59:59",$now));
    return $over - $now;
}

/**
 * 把用户id替换成用户名
 * @param $data
 * @param $userName
 * @return mixed
 */
function dealName($data,$userName){
    foreach($data as $key=>$value){
        foreach($userName as $k=>$v){
            if($data[$key]['user_id'] == $k){
                $data[$key]['name'] =$userName[$k];
            }
        }
    }
    return $data;
}